<?php
Yii::import("application.logic.admin.categoryLogic", true);

class CategoryController extends AdminController
{
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    //public $layout='//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl',     // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }//End filters

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array (
            array (
                'allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'    => array( 'index',
                                       'editpage',
                                       'edit',
                                       'delete',
                                       'save',
                                       'importPage',
                                       'execImport'
                                     ),
                'users'      => array('@'),
                'expression' => 'Yii::app()->user->authority == Account::ADMIN'
            ),
            array (
                'deny', // deny all users
                'users' => array('*'),
            )
        );
    }//End accessRules

    /**
     * Show index page of category manager
     *
     * @author  TuanNguyen
     * @version Created 2013-08-15
     * @param
     * @return  void
     */
    public function actionIndex()
    {
        //init
        $categoryLogic  = new categoryLogic();

        //Set default param for get list of category
        $categoryLogic->setDefaultParam(true);

        //Get list of category
        $categoryLogic->getCategoryListWithLimit();

        $this->render(
            'index',
            array(
                'arr_data'         => $categoryLogic->categoryList,
                'i_totalItem'      => $categoryLogic->paramList['dataTotal'],
                'i_amountPerPage'  => $categoryLogic->paramList['dataPerPage'],
                'i_currentPage'    => $categoryLogic->paramList['page'],
                's_columnLabel'    => $categoryLogic->paramList['columnLabel'],
                's_sortMethod'     => $categoryLogic->paramList['sortMethod'],
                'i_columnPosition' => $categoryLogic->paramList['columnPosition'],
                's_filter'         => $categoryLogic->paramList['filter']
            )
        );//End render
    }//End actionIndex


    /**
     * Show Adding page of category manager
     *
     * @author  TuanNguyen
     * @version Created 2013-08-15
     * @param
     * @return  void
     */
    public function actionEditpage()
    {
        //init
        $categoryLogic  = new categoryLogic();

        //Set default param for get list of category
        $categoryLogic->setDefaultParam();

        //Get list of category
        $categoryLogic->getCategoryListWithLimit();

        //Get category list with level order
        $categoryLogic->levelCategoryList = $categoryLogic->initLevelCategoryList();

        $this->render(
            'editpage',
            array(
                'arr_category' => $categoryLogic->levelCategoryList,
                'bool_IE'      => $categoryLogic->paramList['isIEBrowser']
            )
        );
    }//End actionEditpage


    /**
     * Show edit page of category manager
     *
     * @author  TuanNguyen
     * @version Created 2013-08-15
     * @param
     * @return  void
     */
    public function actionEdit()
    {
        //init
        $categoryLogic  = new categoryLogic();
        $s_errorMessage = null;

        //Set default param for get list of category
        $categoryLogic->setDefaultParam();

        //Get list of category
        $categoryLogic->getCategoryListWithLimit();

        //Get category list with level order
        $categoryLogic->levelCategoryList = $categoryLogic->initLevelCategoryList();

        //Get category from request in webForm
        $b_result = $categoryLogic->getCategoryByRequest();
        if ( !$b_result ) {
            $s_errorMessage = self::getErrorMessage($categoryLogic->errorList);
        }

        $this->renderPartial(
            'edit',
            array(
                'o_model'      => $categoryLogic->paramList['requestCategory'],
                'i_key'        => $_POST['i_key'],
                'arr_category' => $categoryLogic->levelCategoryList,
                'bool_IE'      => $categoryLogic->paramList['isIEBrowser'],
                's_errorMsg'   => $s_errorMessage 
            )
        );
    }//End actionEdit


    /**
     * Show saving result of category manager
     * with JSON encode
     *
     * @author  TuanNguyen
     * @version Created 2013-08-15
     * @param
     * @return  void
     */
    public function actionSave()
    {
        //init
        $categoryLogic  = new categoryLogic();
        $s_errorMessage = null;

        $b_result = $categoryLogic->checkEditRequest();
        if ( !$b_result ) {
            $s_errorMessage = self::getErrorMessage($categoryLogic->errorList);
            $arr_result     = array('error' => $s_errorMessage);
            exit(json_encode($arr_result));
        }

        $b_result = $categoryLogic->executeRequestCategory();
        if ( !$b_result ) {
            $s_errorMessage = self::getErrorMessage($categoryLogic->errorList);
            $arr_result     = array('error' => $s_errorMessage);
            exit(json_encode($arr_result));
        }

        exit(json_encode( $categoryLogic->paramList['requestCategory']->getAttributes(array('key','name','image','parent_name','insert'))));
        
    }//End actionSave


    /**
     * Show deleting result of category manager
     * with JSON encode
     *
     * @author  TuanNguyen
     * @version Created 2013-08-15
     * @param
     * @return  void
     */
    public function actionDelete()
    {
        //init
        $categoryLogic  = new categoryLogic();
        $s_errorMessage = null;

        $b_result = $categoryLogic->checkDeleteRequest();
        if ( !$b_result ) {
            $s_errorMessage = self::getErrorMessage($categoryLogic->errorList);
            $arr_result     = array('error' => $s_errorMessage);
            exit(json_encode($arr_result));
        }

        $b_result = $categoryLogic->deleteRequestIds();
        if ( !$b_result ) {
            $s_errorMessage = self::getErrorMessage($categoryLogic->errorList);
            $arr_result     = array('error' => $s_errorMessage);
            exit(json_encode($arr_result));
        }

        $arr_result = array('result' => 1);
        exit(json_encode($arr_result));
    }

    /**
     * Show import page of category manager
     *
     * @author  TuanNguyen
     * @version Created 2013-08-15
     * @param
     * @return  void
     */
    public function actionImportPage()
    {
        $this->render(
            'importPage',
            array()
        );
    }//End actionImportPage


    /**
     * Show import result of category manager
     *
     * @author  TuanNguyen
     * @version Created 2013-08-15
     * @param
     * @return  void
     */
    public function actionExecImport()
    {
        //init
        $categoryLogic  = new categoryLogic();
        $arr_errCode    = array();
        $s_errorMessage = null;

        //Set request param into paramList of categoryLogic
        $categoryLogic->setUploadingParam();

        //Get data from uploaded file to insert
        $categoryLogic->getDataFromUploadedFile();

        //Insert or update data into database
        $categoryLogic->execUploadedDataToDatabase();

        //Set error message, if there are error code in list
        if ( count($categoryLogic->errorList) > 0 ) {
            $s_errorMessage = self::getErrorMessage($categoryLogic->errorList);
        }

        $this->renderPartial(
            'importResult',
            array(
                'categoryList' => $categoryLogic->categoryList,
                'errorMessage' => $s_errorMessage,
                'successCount' => $categoryLogic->paramList['successCount'],
                'failingCount' => $categoryLogic->paramList['failingCount']
            )
        );

        Yii::app()->end();
        return true;
    }//End actionUploadPreview


    /**
     * Get error message from error code
     *
     * @author  TuanNguyen
     * @version Created 2013-08-15
     * @param
     * @return  void
     */
    private function getErrorMessage($errorEnts)
    {
        $arr_errorMessage    = array (
            'ERR_1' => 'Có lỗi trong việc truy xuất dữ liệu.',
            'ERR_2' => 'PARAM_1',
            'ERR_3' => 'PARAM_1 bị thiếu, xin hãy tải lại trang.',
            'ERR_4' => '"PARAM_1" phải là PARAM_2, và không được để trống. PARAM_LINE',
            'ERR_5' => 'PARAM_1 chưa được nhập. PARAM_LINE',
            'ERR_6' => 'Không tồn tại dữ liệu danh mục PARAM_1. PARAM_LINE',
            'ERR_7' => 'Không có danh mục nào được chọn.',
            'ERR_8' => 'There are an error, we can not save your data.',
                        
        );

        //Return error message
        if ( is_array($errorEnts) ) {
            return ErrorEntity::setErrorMessageByArray($errorEnts, $arr_errorMessage);
        } elseif ( $errorEnts instanceof ErrorEntity ) {
            return ErrorEntity::setErrorMessageByEntity($errorEnts, $arr_errorMessage);
        }
    }//End getErrorMessage
}